package com.ruoyi.basicdata.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.ruoyi.basicdata.domain.Resident;
import com.ruoyi.basicdata.dto.LoginDto;
import com.ruoyi.basicdata.dto.UserDto;
import com.ruoyi.basicdata.feign.MissionFeign;
import com.ruoyi.basicdata.mapper.ResidentMapper;
import com.ruoyi.basicdata.utils.AesUtil;
import com.ruoyi.basicdata.utils.Cons;
import com.ruoyi.basicdata.utils.StrUtils;
import com.ruoyi.basicdata.utils.VerifyCodeUtils;
import com.ruoyi.basicdata.vo.HslogVo;
import com.ruoyi.basicdata.vo.LoginVo;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.basicdata.mapper.UserMapper;
import com.ruoyi.basicdata.domain.User;
import com.ruoyi.basicdata.service.IUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 用户管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-04-05
 */
@Service
public class UserServiceImpl implements IUserService 
{
    @Resource
    private UserMapper userMapper;

    @Resource
    private ResidentMapper residentMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private MissionFeign missionFeign;



    /**
     * 查询用户管理
     * 
     * @param id 用户管理主键
     * @return 用户管理
     */
    @Override
    public User selectUserById(Long id)
    {
        return userMapper.selectUserById(id);
    }

    /**
     * 查询用户管理列表
     * 
     * @param user 用户管理
     * @return 用户管理
     */
    @Override
    public List<User> selectUserList(User user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增用户管理
     * 
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public int insertUser(User user)
    {
        return userMapper.insertUser(user);
    }

    /**
     * 修改用户管理
     * 
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public int updateUser(User user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除用户管理
     * 
     * @param ids 需要删除的用户管理主键
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] ids)
    {
        return userMapper.deleteUserByIds(ids);
    }

    /**
     * 删除用户管理信息
     * 
     * @param id 用户管理主键
     * @return 结果
     */
    @Override
    public int deleteUserById(Long id)
    {
        return userMapper.deleteUserById(id);
    }


    /**
     * 图片验证码
     * @param key
     * @return
     */
    @Override
    public String imageVerifyCode(String key) throws IOException {
        // 1. 生成验证码
        String verifCode = StrUtils.getComplexRandomString(4);
        // 2. 将验证码传入到redis中
        redisTemplate.opsForValue().set(key,verifCode,3, TimeUnit.MINUTES);
        // 3. 将随机生成的验证码转为Base64位,并返回
        return VerifyCodeUtils.VerifyCode(115, 45, verifCode);
    }

    /**
     *  用户登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult login(LoginDto dto) throws Exception {
        User user =userMapper.selectUserByUsername(dto.getUsername());
        if (null == user){
            return AjaxResult.error(-1,"账户不存在");
        }
        if (!dto.getPassword().equals(user.getPassword())){
            return AjaxResult.error(-1,"账户或者密码错误");
        }

        Long reidentId = user.getReidentId(); //获取到住户id 以便用来获取住户当前任务
        AjaxResult ajaxResult = missionFeign.getMissNameByResidentId(reidentId);
        Object missNameByResidentId = ajaxResult.get("nuclein_mission_id");

        LoginVo loginVo = new LoginVo();
        String a = AesUtil.Encrypt(user.getId().toString(), Cons.KEY);
        String b = AesUtil.Encrypt(missNameByResidentId.toString(), Cons.KEY);
        loginVo.setUser(a);
        loginVo.setTask(b);

        return AjaxResult.success("登录成功",loginVo);
    }


    /**
     * 二维码扫码之后信息回显
     * @param vo
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult returnMessage(LoginVo vo) throws Exception {
        // 先进行解密
        String MissionId = AesUtil.Decrypt(vo.getTask(), Cons.KEY);// 楼栋核酸任务Id
        String userId = AesUtil.Decrypt(vo.getUser(), Cons.KEY); // 用户Id
        if (null == userId || null == MissionId){
            return AjaxResult.error("解密失败");
        }

        User user = userMapper.selectUserById(Long.valueOf(userId));
        Resident resident = residentMapper.selectResidentById(Long.valueOf(user.getReidentId()));
        AjaxResult missName = missionFeign.getMissNameByMissionId((Long.valueOf(MissionId)));


        HslogVo hslogVo = new HslogVo();
        hslogVo.setResidentId(resident.getId());
        hslogVo.setPhone(user.getPhone());
        hslogVo.setName(user.getUsername());
        hslogVo.setMissionName((String) missName.get("msg"));
        return AjaxResult.success(hslogVo);
    }

    /**
     *  用户注册
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult register(UserDto dto) {
        // 1. 校验参数
        // 2.条件判断（）
        String imgCodeKey = (String) redisTemplate.opsForValue().get(dto.getUuid());
        if (StringUtils.isBlank(imgCodeKey)){
            return AjaxResult.error(-1,"验证码错误");
        }
        if (!imgCodeKey.equalsIgnoreCase(dto.getCode())){
            return AjaxResult.error(-1,"验证码错误");
        }
        // 3.保存数据
        // 先保存住户表
        Resident resident = new Resident();
        resident.setVillageId(dto.getVillageId());
        resident.setBuildingId(dto.getBuildingId());
        resident.setResidentName(dto.getUsername());
        resident.setResidentPhone(dto.getPhone());
        resident.setResidentAddress(dto.getBuildingAddress());
        resident.setState(0L);
        residentMapper.insertResident(resident);

        // 保存用户表
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setGender(dto.getGender());
        user.setPhone(dto.getPhone());
        user.setPassword("123456");
        user.setWx(dto.getWx());
        user.setReidentId(resident.getId());
        userMapper.insertUser(user);
        return AjaxResult.success();
    }
}
